<script setup lang="ts">
import { ref } from 'vue'
import { getCode, login } from '@/api/auth';
import type { CodeResult, LoginParam, Token } from '@/api/auth/types';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { useTokenStore } from '@/stores/useTokenStore';
const route = useRoute()
const router = useRouter()
const tokenStore = useTokenStore()
const codeUrl = ref('')
const loginRef = ref()
const loginForm = ref<LoginParam>({
    username: '',
    password: '',
    uuid: '',
    code: '',

})
const LoginFormRules = ref<FormRules>({
    username: [{ required: true, message: '请输入用户姓名' }],
    password: [{ required: true, message: '请输入用户密码' }],
    code: [{ required: true, message: '请输入验证码' }],

})
const resetLoginForm = () => {
    loginRef.value.resetFields()
    getVerifyCode()
}
const getVerifyCode = () => {
    getCode().then((resp: CodeResult) => {
        codeUrl.value = resp.codeUrl
        loginForm.value.uuid = resp.uuid
    }).catch(e => {
        console.log(e)
        getVerifyCode()
    })
}
const confirm = () => {
    loginRef.value.validate((v: boolean) => {
        if (v) {
            login(loginForm.value).then((resp: Token) => {
                tokenStore.setToken(resp)
                ElMessage.success('登录成功')
                router.push({ path: route.query.destPath ? route.query.destPath as string : '/' })
            }).catch(e => console.log(e))
        }
    })
}
getVerifyCode()
</script>

<template>
    <el-card class="login-card">
        <el-form ref="loginRef" :model="loginForm" :rules="LoginFormRules" label-width="80">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input placeholder="请输入密码" type="password" v-model="loginForm.password"></el-input>
            </el-form-item>
            <el-row :gutter="15">
                <el-col :span="18">
                    <el-form-item label="验证🐎" prop="code">
                        <el-input v-model="loginForm.code" placeholder="请输入验证码" />
                    </el-form-item></el-col>
                <el-col :span="6">
                    <el-image :src="codeUrl" @click="getVerifyCode" /></el-col>
            </el-row>

            <el-form-item>
                <el-button type="primary" plain @click="confirm">登录</el-button>
                <el-button type="info" plain @click="resetLoginForm">重置</el-button>
            </el-form-item>

        </el-form>
    </el-card>



</template>

<style scoped>
.login-card {
    width: 400px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);

}
</style>